package com.oliver.oliveraiagent.chatMemory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oliver.oliveraiagent.model.entity.ChatMessage;
import com.oliver.oliveraiagent.service.ChatMessageService;
import com.oliver.oliveraiagent.utils.MessageConverter;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName MySQLBasedChatMemory
 * @Description TODO
 * @Author snow
 * @Date 2025/5/2 0:53
 **/

/**
 * 基于MySQL的对话记忆实现
 */
@Component
public class MySQLBasedChatMemory implements ChatMemory {

    @Resource
    private ChatMessageService chatMessageService;

    @Override
    public void add(String conversationId, List<Message> messages) {
        //  需要在这里获取到用户的userId，然后在保存消息的时候携带对应的userId
        List<ChatMessage> chatMessageList = messages.stream()
                .map(message -> MessageConverter.toChatMessage(message, conversationId))
                .collect(Collectors.toList());

        chatMessageService.saveBatch(chatMessageList, chatMessageList.size());
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<ChatMessage> list = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getConversationId, conversationId)
                .orderByAsc(ChatMessage::getCreateTime)
                .last(lastN > 0 , "limit " + lastN)
                .list();

        return list.stream()
                .map(MessageConverter::toMessage)
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<ChatMessage>();
        wrapper.eq(ChatMessage::getConversationId, conversationId);

        chatMessageService.remove(wrapper);
    }
}
